/**
 * @Author Fizz Pu
 * @Date 2020/11/5 下午8:44
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */

import java.util.Arrays;

/**
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 *
 *
 * 示例1
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 */

class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
 }

public class Offer6 {

    // 反转链表, 头插法
    public int[] reversePrint(ListNode head) {
        if(head == null) return new int[0];
        int count = 0;
        ListNode first = new ListNode(-1);
        ListNode cur = head;
        ListNode next;

        while (cur != null){
            // 提前保存下一个节点
            next = cur.next;
            cur.next = first.next;
            first.next = cur;
            cur = next;
            count++;
        }

        int[] res = new int[count];
        int i = 0;
        cur = first.next;
        while (cur != null){
            res[i] = cur.val;
            cur = cur.next;
            i++;
        }

        return res;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(0);
        node.next = new ListNode(1);
        node.next.next = new ListNode(2);

        Offer6 offer6 = new Offer6();
        System.out.println(Arrays.toString(offer6.reversePrint(node)));
    }
}
